﻿using System;
using System.Net.Sockets.Kcp;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ThreeUDP
{
    class Program
    {
        static void Main(string[] args)
        {

            //初始化路由
            var route1 = new Route();
            const int conv = 123;
            var kcp1 = new PoolSegManager.Kcp(conv, route1);

            kcp1.NoDelay(1, 10, 2, 1);//fast
            kcp1.WndSize(64, 64);
            kcp1.SetMtu(512);



            //事件处理
            route1.Out += buffer =>
            {
                Task.Run(() =>
                {
                     //kcp2.Input(buffer.Span);
                });
            };

            //
            int count = 0;
            route1.Recv += buffer =>
            {
                
                //接受到消息
                var str = Encoding.ASCII.GetString(buffer);
                count++;
                Console.WriteLine($"kcp1 recv {count} ----{str}");


                //广播
                var res = kcp1.Send(buffer);
                if (res != 0)
                {
                    Console.WriteLine($"kcp send error");
                }
            };
            

            //循环监听
            Task.Run(async () =>
            {
                try
                {
                    int updateCount = 0;
                    while (true)
                    {
                        kcp1.Update(DateTime.UtcNow);

                        int len;
                        while ((len = kcp1.PeekSize()) > 0)
                        {
                            var buffer = new byte[len];
                            if (kcp1.Recv(buffer) >= 0)
                            {
                                route1.Receive(buffer);
                            }
                        }

                        await Task.Delay(5);
                        updateCount++;
                        if (updateCount % 1000 == 0)
                        {
                            Console.WriteLine($"KCP1 ALIVE {updateCount}----");
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }

            });


            var sendbyte = Encoding.ASCII.GetBytes("hello client!!!");
            kcp1.Send(sendbyte);

            while (true)
            {
                Thread.Sleep(1000);
                GC.Collect();
            }

            Console.ReadLine();
        }
    }
}
